﻿namespace wToggl
{
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;

    public sealed partial class BackgroundWorkOverlay : UserControl
    {
        public static readonly DependencyProperty IsVisibleProperty = DependencyProperty.RegisterAttached(
            "IsVisible",
            typeof(bool),
            typeof(BackgroundWorkOverlay),
            new PropertyMetadata(default(bool), IsVisibleChangedCallback));

        public static readonly DependencyProperty OverlayMessageProperty = DependencyProperty.RegisterAttached(
            "OverlayMessage",
            typeof(string),
            typeof(BackgroundWorkOverlay),
            new PropertyMetadata(default(string), MessageChangedCallback));

        private static void MessageChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
        {
            var obj = dependencyObject as BackgroundWorkOverlay;

            if (obj == null)
            {
                return;
            }

            var message = dependencyPropertyChangedEventArgs.NewValue as string;
            obj.MessageBox.Text = message;
        }

        public static void SetOverlayMessage(DependencyObject element, string value)
        {
            element.SetValue(OverlayMessageProperty, value);
        }

        public static string GetOverlayMessage(DependencyObject element)
        {
            return (string)element.GetValue(OverlayMessageProperty);
        }

        private static void IsVisibleChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
        {
            var obj = dependencyObject as BackgroundWorkOverlay;

            if (obj == null)
            {
                return;
            }

            if (!(dependencyPropertyChangedEventArgs.NewValue is bool))
            {
                return;
            }

            var value = (bool)dependencyPropertyChangedEventArgs.NewValue;

            obj.OverlayGrid.Visibility = value ? Visibility.Visible : Visibility.Collapsed;
            obj.ProgressCircle.IsActive = value;
        }

        public static void SetIsVisible(DependencyObject element, bool value)
        {
            element.SetValue(IsVisibleProperty, value);
        }

        public static bool GetIsVisible(DependencyObject element)
        {
            return (bool)element.GetValue(IsVisibleProperty);
        }

        public BackgroundWorkOverlay()
        {
            this.InitializeComponent();
        }
    }
}
